import getLocation from '../../../wxjs/getLocation.js'
import navToNext from '../../../wxjs/navToNext.js'
import Paging from '../../../wxjs/Paging.js'
const app = getApp();
var pag = new Paging();

var data = {
  xhx_images: app.xhx_images,
  xhx_route: app.xhx_route,
  xbodyMsg: "请稍等...",
  couponsList: {},
  list: [],
};

var currentPage = {
  data,
  listParams: {},
  reqUrl: app.serAddrs.getActivtyAndCoupont,
  form: {}, //详情请求参数
  payParam: {}, //支付参数
  onLoad,
  onShow,
  onHide,
  onShareAppMessage,
  setTimmer,
  getCountDown,
  orderDetail, //获取商品详情
  wxPay,
  payment,
  refund,
  refundAjax,
  getCoupons,
  callBack,
  receiveCoupon,
  requestReceive
};

var page = Object.assign({}, getLocation, navToNext, pag.func(), currentPage);

Page(page);

function onLoad(options) {
  const that = this;
  const uuid = options && options.uuid || "";
  that.form.uuid = uuid;
  that.getCoupons();
  that.orderDetail();

}

function getCoupons() {
  const that = this;
  that.listParams.activityTypeId = 0;
  that.listParams.orderUuid = that.form.uuid;
  that.listParams.page = 1; //当前页数
  that.listParams.row = 99999; //1页的条数
  that.getPageList();
}

function callBack(res) {
  const that = this;
  var obj = {
    list: res.data,
    receive: that.receiveCoupon
  };
  that.setData({
    couponsList: obj,
    lists: []
  })
}

function receiveCoupon(data) {
  const that = this;
  data.wxMold = 1;
  data.userId = app.userInfo.userId;
  data.orderUuid = that.form.uuid;
  console.log('==============', data)
  if (data.activityTypeId == 4) {
    console.log('fffffffffffffffffff')
    that.onShareAppMessage();
  }
  that.requestReceive(data);
}

function onShareAppMessage() {
  const that = this;
  const uuid = that.form.uuid;
  return {
    title: '',
    path: app.xhx_route.leagueList + "?uuid=" + uuid,
  }
}

function requestReceive(data) {
  const that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.joinInActivtyAndCoupont,
    data: data,
    cancelToast: true,
    complete: function(res) {
      app.middleware.showToast(res && res.msg || "操作失败");
      that.getCoupons();
    },
  })
}

function onShow() {
  const that = this;
  that.setTimmer();
}

function onHide() {
  const that = this;
  if (that.timmer) {
    clearInterval(that.timmer);
    that.setData({
      countDown: 0
    })
  }
}

function setTimmer() {
  const that = this;
  const xbody = that.data.xbody;
  that.onHide();
  if (xbody && xbody.orderStatus == 0) {
    that.getCountDown();
    that.timmer = setInterval(() => {
      that.getCountDown();
    }, 1000);
  }
}

function getCountDown() {
  const that = this;
  const xbody = that.data.xbody;

  let endMsec = app.middleware.time(0, Number(xbody.createTimeStamp) * 1000).msec + 30 * 60 * 1000;
  let s = (endMsec - app.middleware.time().msec) / 1000;
  let countDown = 0,
    minute = 0,
    second = 0,
    temp = {};

  if (s > 0) {
    minute = Math.floor(s / 60);
    second = Math.round(s - minute * 60);
    if (minute < 10) minute = "0" + minute;
    if (second < 10) second = "0" + second;
    temp.countDown = minute + ":" + second;
  } else {
    clearInterval(that.timmer);
    xbody.orderStatus = -1;
    temp.xbody = xbody;
    temp.countDown = 0;
  }
  that.setData(temp)
}

function orderDetail() {
  const that = this;

  app.middleware.requestAjax({
    serAddr: app.serAddrs.orderDetail,
    data: that.form,
    cancelToast: true,
    success: function(res) {
      let xbody = res.data || {};
      let validityDate = app.middleware.time(0, xbody.validityDate);
      xbody.time = validityDate.typeA;
      xbody.week = `(周${validityDate.weekText})`;
      if (xbody.activateNum) xbody.activateNum = xbody.activateNum.replace(/(\d\d\d\d)/g, '$1 ')
      that.setData({
        xbodyMsg: "",
        xbody
      });
      that.payParam.orderUuids = xbody.uuid;
      that.setTimmer();
    },
    fail: function(res) {
      that.setData({
        xbodyMsg: res && res.msg || "请求失败"
      })
    }
  })
}

function wxPay() {
  const that = this;

  app.middleware.requestAjax({
    serAddr: app.serAddrs.wxPay,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    data: that.payParam,
    cancelToast: true,
    success: function(res) {
      that.payment(res.data)
    },
    fail: function(res) {
      app.middleware.showToast(res && res.msg || "请求失败");
    }
  })

}

function payment(data) {
  const that = this;

  wx.requestPayment({
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.prepayId,
    signType: data.signType,
    paySign: data.paySign,
    success(res) {
      that.setData({
        xbodyMsg: "订单更新中..."
      })
      setTimeout(() => {
        that.orderDetail();
        var prevPage = getCurrentPages()[getCurrentPages().length - 2];
        if (app.xhx_route.orderList.indexOf(prevPage.route) != -1) {
          // 初始化
          prevPage.pageListInit();
        }
      }, 2000)
    },
    fail(res) {
      app.infoLog(res)
    }
  })
}

function refund() {
  const that = this;

  var dialogValue = {
    showDialog: true,
    title: '提示',
    content: '全额退款',
    confirmText: '取消',
    cancelText: '确定退款',
    confirm: function(res) {

    },
    cancel: function(res) {
      that.refundAjax();
    }
  }
  that.setData({
    dialogValue: dialogValue
  })
}

function refundAjax() {
  const that = this;
  app.middleware.requestAjax({
    serAddr: app.serAddrs.refund,
    data: that.form,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
    },
    success: function(res) {
      that.orderDetail();
      that.getCoupons();
      var prevPage = getCurrentPages()[getCurrentPages().length - 2];
      if (app.xhx_route.orderList.indexOf(prevPage.route) != -1) {
        // 初始化
        prevPage.pageListInit();
      }
    },
    fail: function(res) {
      wx.showModal({
        title: '提示',
        content: res && res.msg || "请求失败",
        showCancel: false,
      })
    }
  })
}